//
//  LoginViewController.m
//  us
//
//  Created by karry on 2025/3/28.
//

#import "LoginViewController.h"
#import "LoginTypeView.h"
#import "LoginPhoneViewController.h"
#import "PushTransitionAnimator.h"
#import "NavigationControllerDelegate.h"

#import "CharacterViewController.h"
#import "SceneDelegate.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import <SafariServices/SafariServices.h>
#import <WXApi.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

#import <JPUSHService.h>

@import Lottie;

@interface LoginViewController ()<LoginTypeViewDelegate,TencentSessionDelegate,ASAuthorizationControllerDelegate,ASAuthorizationControllerPresentationContextProviding>

@property (nonatomic, strong) LottieWrapper *lottieWrapper;

@property (nonatomic, strong) UIImageView *bgImgView;

@property (nonatomic, strong) UILabel *welcomeLab;
@property (nonatomic, strong) UILabel *beginLab;

@property (nonatomic, strong) UIButton *phoneBtn;
@property (nonatomic, strong) UIImageView *phoneImageView;
@property (nonatomic, strong) UILabel *phoneLab;

@property (nonatomic, strong) LoginTypeView *bottomView;

@property (nonatomic, strong) NavigationControllerDelegate *navDelegate;

@end

@implementation LoginViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.hidden = NO;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.bgImgView];
    [self.bgImgView addSubview:self.welcomeLab];
    [self.bgImgView addSubview:self.beginLab];
    [self.bgImgView addSubview:self.phoneBtn];
    [self.bgImgView addSubview:self.phoneImageView];
    [self.bgImgView addSubview:self.phoneLab];

    self.bottomView = [LoginTypeView jk_loadInstanceFromNib];
    self.bottomView.delegate = self;
    [self.view addSubview:self.bottomView];


    self.bgImgView.alpha = 0.f;
    self.bottomView.alpha = 0.f;
    
    CGFloat scale = 144.0/50.0;
    CGFloat height = ScreenWidth/scale;
    CGRect frame = CGRectMake(0, (ScreenHeight - height)/2, ScreenWidth, height);

    [self.lottieWrapper setFrame:frame];
    [self.lottieWrapper addToView:self.view];
    [self.lottieWrapper playAnimation];

    CGFloat duration = [self.lottieWrapper getAnimationDuration];
//    NSLog(@"动画时长: %f 秒", duration);
    
    [self initLayout];
    
    [self.view layoutIfNeeded];
    
    [self finshLayout];
    
    [UIView animateWithDuration:1.f
                          delay:duration - 2.f
         usingSpringWithDamping:0.6
          initialSpringVelocity:0.6
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                
        self.bgImgView.alpha = 1.f;
        self.bottomView.alpha = 1.f;
        [self.view layoutIfNeeded];
        self.bgImgView.transform = CGAffineTransformIdentity;
        
        
        CGFloat newScale = (ScreenWidth - 64) / ScreenWidth;
        self.lottieWrapper.animationView.transform = CGAffineTransformMakeScale(newScale, newScale);
        self.lottieWrapper.animationView.center = CGPointMake(ScreenWidth / 2, 154 + height / 2);
        
 
    } completion:^(BOOL finished) {
        
    }];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginThirdWithCode:) name:@"WXLogin" object:nil];

}

/// 第三方登录请求us接口
- (void)authLogint:(NSDictionary *)params withPostApi:(NSString *)postApi{
   
    [[EMNetWork shareManager]em_post:postApi params:params hud:@"" showError:YES success:^(EMApiModel *api) {
        if (api.success == NO) {
             return;
        }
 
        USUser *user = [USUser mj_objectWithKeyValues:api.data];
        if (api.data[@"user"]) {
            user = [USUser mj_objectWithKeyValues:api.data[@"user"]];
        }
        [USUser saveUser:user];

        
        ///登录成功后，更新推送的信息。
        [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
            if (registrationID.length > 0) {
                ///更新 registrationID
            
                [[EMNetWork shareManager] em_post:API_EditUser
                                           params:@{@"registrationId":registrationID}
                                              hud:nil
                                       showError:NO
                                          success:^(EMApiModel *api) {
           
                } fail:^{
                     
                    
                }];
            }
        }];
        
        
        [[EMClient sharedClient] loginWithUsername:user.imUserName token:user.imToken completion:^(NSString * _Nonnull aUsername, EMError * _Nullable aError) {
            if (aError) {
                NSLog(@"环信登录失败 ---- %li,%@",aError.code,aError);

            }else {
                NSLog(@"环信登录成功");
            }
        }];
        
        if (user.isNew) {
            CharacterViewController *vc = [[CharacterViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }else{

            UIWindowScene *scene = (UIWindowScene *)[UIApplication sharedApplication].connectedScenes.allObjects.firstObject;
            
            SceneDelegate *sceneDelegate = (SceneDelegate *)scene.delegate;
            
            [sceneDelegate switchToMainInterface];
        }
        
     
    } fail:^{
        
    }];
 

  
}


#pragma mark - 第三方登录
- (void)loginThirdWithCode:(NSNotification *)notification {
    NSString *code = notification.object;
    
    NSDictionary *params = @{@"authSource":@"us_wechat_open",
                             @"systemType":@"1",
                             @"callback":@{@"code":code?:@""}};
 
    [self authLogint:params withPostApi:API_AuthLogint];
}


#pragma mark - LoginTypeViewDelegate
- (void)loginWithWechat {
    SendAuthReq* req =[[SendAuthReq alloc]init];
    req.scope = @"snsapi_userinfo";
    req.state = @"Us";
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req completion:^(BOOL success) {
    }];
}
- (void)loginWithApple {
    ASAuthorizationAppleIDProvider *provider = [[ASAuthorizationAppleIDProvider alloc] init];
    ASAuthorizationAppleIDRequest *request = [provider createRequest];
    request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
    
    ASAuthorizationController *controller = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
    controller.delegate = self;
    controller.presentationContextProvider = self;
    [controller performRequests];
}
- (void)loginWithQQ {
    [TencentOAuth setIsUserAgreedAuthorization:YES];

    [[TencentOAuth sharedInstance]setupAppId:QQAPPID enableUniveralLink:YES universalLink:nil delegate:self];
 
    [[TencentOAuth sharedInstance] authorize:[NSMutableArray arrayWithObjects: kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,nil]];
 
}
- (void)loginTypeViewDidTapTerms:(LoginTypeView *)view{
    
    SFSafariViewController *vc = [[SFSafariViewController alloc]initWithURL:[NSURL URLWithString:@"http://www.emmo.club/us/privacyAgreement_cn.html"]];
    [self presentViewController:vc animated:YES completion:nil];
    
}
- (void)loginTypeViewDidTapPrivacy:(LoginTypeView *)view {
    SFSafariViewController *vc = [[SFSafariViewController alloc]initWithURL:[NSURL URLWithString:@"http://www.emmo.club/us/userAgreement_cn.html"]];
    [self presentViewController:vc animated:YES completion:nil];
    
}

#pragma mark - ASAuthorizationControllerDelegate

// 登录成功
- (void)authorizationController:(ASAuthorizationController *)controller
   didCompleteWithAuthorization:(ASAuthorization *)authorization {
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        ASAuthorizationAppleIDCredential *credential = (ASAuthorizationAppleIDCredential *)authorization.credential;

        NSString *userID = credential.user;
        NSPersonNameComponents *fullName = credential.fullName;
        NSString *email = credential.email;

        NSLog(@"Apple 登录成功: userID: %@, fullName: %@, email: %@", userID, fullName, email);
   
        NSDictionary *params = @{@"sub":userID};
     
        [self authLogint:params withPostApi:API_Login];
    }
}

// 登录失败
- (void)authorizationController:(ASAuthorizationController *)controller
           didCompleteWithError:(NSError *)error {
    NSLog(@"Apple 登录失败: %@", error.localizedDescription);
}
#pragma mark - ASAuthorizationControllerPresentationContextProviding

- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller {
    return self.view.window;
}

#pragma mark -TencentLoginDelegate
- (void)tencentDidLogin{
    
    /** Access Token凭证，用于后续访问各开放接口 */
    if ([TencentOAuth sharedInstance].accessToken) {
        [[TencentOAuth sharedInstance]getUserInfo];
    }else{
        NSLog(@"accessToken 没有获取成功");
    }
}
- (void)tencentDidNotLogin:(BOOL)cancelled {
     
}

- (void)getUserInfoResponse:(APIResponse*) response{
    NSLog(@" response %@",response.jsonResponse);
    
    NSString *nickname = @"";
    NSString *sex = @"0";
    if ([response.jsonResponse.allKeys containsObject:@"nickname"]) {
        nickname = response.jsonResponse[@"nickname"];
    }
    if ([response.jsonResponse.allKeys containsObject:@"gender"]) {
        if ([response.jsonResponse[@"gender"] isEqualToString:@"男"]) {
            sex = @"1";
        }
    }
    NSDictionary *params = @{@"authSource":@"us_qq",
                             @"systemType":@"1",
                             @"openid":[TencentOAuth sharedInstance].openId?:@"",
                             @"nickname":nickname,
                             @"sex":sex};
 
    [self authLogint:params withPostApi:API_AuthLogint];
}

- (void)tencentDidNotNetWork { 
     
}

- (void)finshLayout{
    
    [self.bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(104);
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft).mas_offset(16);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight).mas_offset(-16);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-12);
    }];
    
    [self.bgImgView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
        make.bottom.mas_equalTo(self.bottomView.mas_top).mas_offset(-44);
        
    }];
    
}

- (void)initLayout{
    
    self.bgImgView.transform = CGAffineTransformMakeScale(1.4, 1.4);
    
    [self.bgImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.left.right.equalTo(self.view);
        make.bottom.mas_equalTo(self.bottomView.mas_top).mas_offset(-44);
        
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(104);
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft).mas_offset(16);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight).mas_offset(-16);
        make.top.mas_equalTo(self.view.mas_bottom);
    }];
    
    [self.welcomeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.bgImgView).offset(16);
        make.centerX.equalTo(self.bgImgView);
    }];
    
    [self.beginLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.welcomeLab.mas_bottom).offset(12);
        make.centerX.equalTo(self.bgImgView);
    }];
    
    [self.phoneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bgImgView.mas_left).offset(32);
        make.right.equalTo(self.bgImgView.mas_right).offset(-32);
        make.height.mas_equalTo(56);
        make.bottom.equalTo(self.bgImgView.mas_bottom).offset(-20);
    }];
    
    [self.phoneImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.phoneBtn);
        make.left.equalTo(self.phoneBtn.mas_left).offset(20);
    }];
    
    [self.phoneLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.phoneBtn);
    }];
}
- (void)loginWithPhone {
    
    LoginPhoneViewController *vc = [LoginPhoneViewController new];
    
    // 只初始化一次，防止 delegate 失效
    if (!self.navDelegate) {
        self.navDelegate = [[NavigationControllerDelegate alloc] init];
    }
    
    UINavigationController *nav = self.navigationController;
    nav.delegate = self.navDelegate;
    
    self.navDelegate.sourceViews = @[self.lottieWrapper.animationView,self.phoneBtn,self.phoneImageView,self.phoneLab];  // 这里可以是 UIImageView / UILabel / UIButton / 任何 UIView
    self.navDelegate.destinationViews = @[vc.iconImageView,vc.codeBtn,vc.phoneImageView,vc.phoneLab];
    
    [nav pushViewController:vc animated:YES];
    
    
}


- (UIImageView *)bgImgView {
    if (_bgImgView == nil) {
        _bgImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"login_bg"]];
        _bgImgView.userInteractionEnabled = YES;
    }
    return _bgImgView;
}

- (UILabel *)welcomeLab {
    if (_welcomeLab == nil) {
        _welcomeLab = [[UILabel alloc]init];
        _welcomeLab.text = @"欢迎来到US";
        _welcomeLab.textAlignment = NSTextAlignmentCenter;
        _welcomeLab.textColor = UIColor.titleColor;
        _welcomeLab.font = [UIFont boldSystemFontOfSize:32];
    }
    return _welcomeLab;
}
- (UILabel *)beginLab {
    if (_beginLab == nil) {
        _beginLab = [[UILabel alloc]init];
        _beginLab.text = @"开启我们的小故事";
        _beginLab.textAlignment = NSTextAlignmentCenter;
        _beginLab.textColor = UIColor.subTitleColor;
        _beginLab.font = [UIFont systemFontOfSize:16];
    }
    return _beginLab;
}
- (UIButton *)phoneBtn {
    if (_phoneBtn == nil) {
        _phoneBtn = [UIButton us_fillButtonWithTitle:@""];
        _phoneBtn.layer.cornerRadius = 14;
        [_phoneBtn addTarget:self action:@selector(loginWithPhone) forControlEvents:UIControlEventTouchUpInside];
    }
    return _phoneBtn;
}
- (UIImageView *)phoneImageView{
    if (_phoneImageView == nil) {
        _phoneImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"login_phone"]];
    }
    return _phoneImageView;
}
- (UILabel *)phoneLab {
    if (_phoneLab == nil) {
        _phoneLab = [[UILabel alloc]init];
        _phoneLab.text = @"手机号码登录";
        _phoneLab.textAlignment = NSTextAlignmentCenter;
        _phoneLab.textColor = [UIColor whiteColor];
        _phoneLab.font = [UIFont systemFontOfSize:16];
    }
    return _phoneLab;
}

- (LottieWrapper *)lottieWrapper {
    if (_lottieWrapper == nil) {
        _lottieWrapper = [[LottieWrapper alloc] initWithName:@"lottie_launch"];
        [_lottieWrapper setLoop:false];
    }
    return _lottieWrapper;
}

 
@end
